import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../services/services.dart';
import '../constants/constants.dart';

/// 音乐进度条组件
/// 显示播放进度并支持拖拽调整播放位置
class MusicProgressBar extends StatefulWidget {
  final double height;
  final Color? activeColor;
  final Color? inactiveColor;
  final Color? thumbColor;
  final bool showTimeLabels;
  final bool interactive;
  final EdgeInsets? padding;

  const MusicProgressBar({
    super.key,
    this.height = 4.0,
    this.activeColor,
    this.inactiveColor,
    this.thumbColor,
    this.showTimeLabels = true,
    this.interactive = true,
    this.padding,
  });

  @override
  State<MusicProgressBar> createState() => _MusicProgressBarState();
}

class _MusicProgressBarState extends State<MusicProgressBar>
    with SingleTickerProviderStateMixin {
  late AnimationController _animationController;
  late Animation<double> _scaleAnimation;
  bool _isDragging = false;
  double _dragValue = 0.0;

  @override
  void initState() {
    super.initState();
    _initAnimations();
  }

  /// 初始化动画
  void _initAnimations() {
    _animationController = AnimationController(
      duration: AppTheme.animationDurationFast,
      vsync: this,
    );
    
    _scaleAnimation = Tween<double>(
      begin: 1.0,
      end: 1.2,
    ).animate(CurvedAnimation(
      parent: _animationController,
      curve: Curves.easeInOut,
    ));
  }

  @override
  void dispose() {
    _animationController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<AudioPlayerService>(
      builder: (context, audioService, child) {
        final currentPosition = audioService.currentPosition;
        final totalDuration = audioService.totalDuration;
        
        // 只在非拖拽状态时更新进度值
        if (!_isDragging) {
          final progress = totalDuration.inMilliseconds > 0
              ? currentPosition.inMilliseconds / totalDuration.inMilliseconds
              : 0.0;
          _dragValue = progress;
        }

        return Padding(
          padding: widget.padding ?? EdgeInsets.zero,
          child: Column(
            children: [
              // 进度条
              _buildProgressSlider(
                audioService,
                _dragValue,
                totalDuration,
              ),
              
              // 时间标签
              if (widget.showTimeLabels)
                _buildTimeLabels(
                  _isDragging
                      ? Duration(
                          milliseconds: (_dragValue * totalDuration.inMilliseconds).round(),
                        )
                      : currentPosition,
                  totalDuration,
                ),
            ],
          ),
        );
      },
    );
  }

  /// 构建进度滑块
  Widget _buildProgressSlider(
    AudioPlayerService audioService,
    double value,
    Duration totalDuration,
  ) {
    final activeColor = widget.activeColor ?? AppTheme.primaryColor;
    final inactiveColor = widget.inactiveColor ?? AppTheme.primaryColor.withOpacity(0.3);
    final thumbColor = widget.thumbColor ?? AppTheme.primaryColor;

    return ScaleTransition(
      scale: _scaleAnimation,
      child: SliderTheme(
        data: SliderTheme.of(context).copyWith(
          trackHeight: widget.height,
          thumbShape: RoundSliderThumbShape(
            enabledThumbRadius: _isDragging ? 8.0 : 6.0,
          ),
          overlayShape: RoundSliderOverlayShape(
            overlayRadius: _isDragging ? 16.0 : 12.0,
          ),
          activeTrackColor: activeColor,
          inactiveTrackColor: inactiveColor,
          thumbColor: thumbColor,
          overlayColor: thumbColor.withOpacity(0.2),
          trackShape: const RoundedRectSliderTrackShape(),
        ),
        child: Slider(
          value: value.clamp(0.0, 1.0),
          onChanged: widget.interactive
              ? (newValue) => _onProgressChanged(newValue)
              : null,
          onChangeStart: widget.interactive
              ? (value) => _onProgressChangeStart()
              : null,
          onChangeEnd: widget.interactive
              ? (value) => _onProgressChangeEnd(audioService, value, totalDuration)
              : null,
        ),
      ),
    );
  }

  /// 构建时间标签
  Widget _buildTimeLabels(Duration currentPosition, Duration totalDuration) {
    return Padding(
      padding: const EdgeInsets.symmetric(
        horizontal: AppTheme.spacingMedium,
        vertical: AppTheme.spacingXS,
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            _formatDuration(currentPosition),
            style: const TextStyle(
              fontSize: AppTheme.fontSizeSmall,
              color: AppTheme.textSecondaryDark,
              fontFeatures: [FontFeature.tabularFigures()],
            ),
          ),
          Text(
            _formatDuration(totalDuration),
            style: const TextStyle(
              fontSize: AppTheme.fontSizeSmall,
              color: AppTheme.textSecondaryDark,
              fontFeatures: [FontFeature.tabularFigures()],
            ),
          ),
        ],
      ),
    );
  }

  /// 进度改变时的处理
  void _onProgressChanged(double value) {
    setState(() {
      _dragValue = value;
    });
  }

  /// 开始拖拽进度条
  void _onProgressChangeStart() {
    setState(() {
      _isDragging = true;
    });
    _animationController.forward();
  }

  /// 结束拖拽进度条
  void _onProgressChangeEnd(
    AudioPlayerService audioService,
    double value,
    Duration totalDuration,
  ) {
    setState(() {
      _isDragging = false;
    });
    _animationController.reverse();
    
    // 跳转到指定位置
    final newPosition = Duration(
      milliseconds: (value * totalDuration.inMilliseconds).round(),
    );
    audioService.seekTo(newPosition);
    
    // 添加短暂延迟，确保seekTo操作有时间生效
    Future.delayed(const Duration(milliseconds: 100), () {
      if (mounted) {
        setState(() {});
      }
    });
  }

  /// 格式化时长
  String _formatDuration(Duration duration) {
    final hours = duration.inHours;
    final minutes = duration.inMinutes.remainder(60);
    final seconds = duration.inSeconds.remainder(60);
    
    if (hours > 0) {
      return '${hours.toString().padLeft(1, '0')}:'
          '${minutes.toString().padLeft(2, '0')}:'
          '${seconds.toString().padLeft(2, '0')}';
    } else {
      return '${minutes.toString().padLeft(1, '0')}:'
          '${seconds.toString().padLeft(2, '0')}';
    }
  }
}

/// 迷你进度条组件
/// 用于在其他页面显示简化的进度条
class MiniProgressBar extends StatelessWidget {
  final double height;
  final Color? activeColor;
  final Color? inactiveColor;
  final bool showTimeLabels;
  final EdgeInsets? padding;

  const MiniProgressBar({
    super.key,
    this.height = 2.0,
    this.activeColor,
    this.inactiveColor,
    this.showTimeLabels = false,
    this.padding,
  });

  @override
  Widget build(BuildContext context) {
    return MusicProgressBar(
      height: height,
      activeColor: activeColor,
      inactiveColor: inactiveColor,
      thumbColor: Colors.transparent,
      showTimeLabels: showTimeLabels,
      interactive: false,
      padding: padding,
    );
  }
}

/// 圆形进度指示器
/// 用于显示圆形的播放进度
class MusicCircularProgressIndicator extends StatelessWidget {
  final double size;
  final double strokeWidth;
  final Color? activeColor;
  final Color? inactiveColor;
  final Widget? child;

  const MusicCircularProgressIndicator({
    super.key,
    this.size = 200.0,
    this.strokeWidth = 4.0,
    this.activeColor,
    this.inactiveColor,
    this.child,
  });

  @override
  Widget build(BuildContext context) {
    return Consumer<AudioPlayerService>(
      builder: (context, audioService, _) {
        final currentPosition = audioService.currentPosition;
        final totalDuration = audioService.totalDuration;
        final progress = totalDuration.inMilliseconds > 0
            ? currentPosition.inMilliseconds / totalDuration.inMilliseconds
            : 0.0;

        return SizedBox(
          width: size,
          height: size,
          child: Stack(
            alignment: Alignment.center,
            children: [
              // 背景圆环
              SizedBox(
                width: size,
                height: size,
                child: CircularProgressIndicator(
                  value: 1.0,
                  strokeWidth: strokeWidth,
                  valueColor: AlwaysStoppedAnimation<Color>(
                    inactiveColor ?? AppTheme.primaryColor.withOpacity(0.2),
                  ),
                  backgroundColor: Colors.transparent,
                ),
              ),
              
              // 进度圆环
              SizedBox(
                width: size,
                height: size,
                child: CircularProgressIndicator(
                  value: progress,
                  strokeWidth: strokeWidth,
                  valueColor: AlwaysStoppedAnimation<Color>(
                    activeColor ?? AppTheme.primaryColor,
                  ),
                  backgroundColor: Colors.transparent,
                ),
              ),
              
              // 中心内容
              if (child != null) child!,
            ],
          ),
        );
      },
    );
  }
}